const fs = require('fs')
const path = require('path')
const lib = require('./commonLib')


//获得括号内的数据
const getInnerData = strfn => str => {
	str.match(/\((.+?)\)/g)
	return JSON.stringify(strfn(RegExp.$1))
}

const getInnerDataNoConvert = strfn => str => {
	str.match(/\((.+?)\)/g)
	return strfn(RegExp.$1)
}


/**
 * code:
 * 	@loadMnemonic
 *  @loadMnemonic(1)
 *  preclsp.json
 *  "@mnemonic":"*",
 *  "@1mnemonic":"*"
 *  get
 *  console.log({$address,$address_1})
 */
const loadMnemonic = (compileFile)=>{

	const _addVar = (num="") => {
		const s = num ? "_"+num : "";
		return `global._MNEMONIC${s} = READ_MNEMONIC(@${num}mnemonic);`+
			   `const {$address:$address${s},$fp:$fp${s},$$sk:$$sk${s},$$pk:$$pk${s},$sk:$sk${s},$pk:$pk${s},$ph:$ph${s}} = global._MNEMONIC${s}`
	}

	compileFile.replaceAll(/@loadMnemonic\([\d]*\)/g,getInnerDataNoConvert(_addVar))

	compileFile.replaceAll(/@loadMnemonic/g,getInnerDataNoConvert(_addVar))

}



//替换数据
exports.convertPlaceHolder = (compileFile,scope) => {


	compileFile.replace(/\/\/.*$/mg, '');

	replaceInstruct(compileFile,"@mark",params => `SHOW_PUZZLE_HASH_INFO(${params})`)


	compileFile.replaceAll(/@include\(.*\)/g,getInnerDataNoConvert(dateStr => {
		const relativeFile = dateStr.replace(/\"/g,"")
		const fileContent = compileFile.getRelativeFile(relativeFile).readFile().content;
		return fileContent.replace(/@deploy\(\d*\)/g,"")
			.replace("#!clsp","")
			.replace("@debug","");
	}))


	loadMnemonic(compileFile)


	//基础数据替换
	for(let p in scope){
		compileFile.replaceAll(p,()=>JSON.stringify(scope[p]))
	}

	//日期转换
	compileFile.replaceAll(/@date\([\d\w-:\s]*\)/g,getInnerData(dateStr => new Date(dateStr).getTime()/1000 ))

	//将数字进行包裹
	compileFile.replaceAll(/@xch\([\d.\s]*\)/g,getInnerData(dateStr => XCH_TO_MOJO(dateStr)))

	//数字
	compileFile.replaceAll(/@mojo\([\d.\s]*\)/g,getInnerData(dateStr => dateStr ))

	compileFile.replaceAll(/@debug/g,getInnerDataNoConvert(dateStr => {
		return "DEBUG()"
	}))

	compileFile.replaceAll(/@mainnet/g,getInnerDataNoConvert(dateStr => {
		return "XCH_ADDRESS_PREFIX='xch'";
	}))

	compileFile.replaceAll(/@summary/g,getInnerDataNoConvert(dateStr => {
		return "COIN_CHANGE_INFO()"
	}))

	compileFile.replaceAll(/@deploy\(\d*\)/g,getInnerDataNoConvert(dateStr => {
		return `DEPLOY(${dateStr})`
	}))

	compileFile.replaceAll(/@balance/g,getInnerDataNoConvert(dateStr => {
		return `SHOW_BALANCE(global._MNEMONIC.$ph)`
	}))

	compileFile.replaceAll(/@balance\(.*\)/g,getInnerDataNoConvert(dateStr => {
		return `SHOW_BALANCE(${dateStr})`
	}))

	compileFile.replaceAll(/@now/g,getInnerDataNoConvert(dateStr => {
		return ~~(new Date().getTime()/1000);
	}))
	
	compileFile.replaceAll(/@minute\(\d*\)/g,getInnerDataNoConvert(num => {
		return num*60;
	}))

}

const replaceInstruct = (compileFile,symbol,cb) => {
	compileFile.mapRows(r => {
		const index = r.indexOf(symbol);
		const lastBracketIndex = r.lastIndexOf(")")
		if(index>=0){

			const params = r.substring(index+symbol.length+1,lastBracketIndex)

			return  cb(params)

		}
		return r;
	})
}

exports.convertTestForClsp = compileFile =>{

	replaceInstruct(compileFile,"@main",params => `BRUN( CURRY(@FileName,[]),'(${params})');`)

}


//搜索用户自定义的配置数据
exports.getConfigFile = (dir,fileName,deep) =>{

	if(!fs.existsSync(dir) || deep === 0){
		return {};
	}

	const jsonFile = path.join(dir,fileName)

	if(fs.existsSync(jsonFile)){
		return JSON.parse(fs.readFileSync(jsonFile, 'utf-8'));
	}else{
		return exports.getConfigFile(path.join(dir,"../"),fileName,deep-1)
	}
	
}


